/**
 * 该文件是用来操作登录、注册、获取用户信息、token 等操作，
 * 📢🔈📣几乎全部需要重写，不分析了 ❗❗❗
 */

import { defineStore } from 'pinia'

// 导入操作 Token 的方法
import { getToken, removeToken, setToken } from '@/utils/token-utils'
import type { UserInfoState } from './interface'
import { allAsyncRoutes, otherRoutes, staticRoutes } from '@/router/routes'
import { reqLogin, reqLogOut, reqUserInfo } from '@/api/user'
import type { userInfo } from '@/api/types'
import type { RouteRecordRaw } from 'vue-router'
import { cloneDeep } from 'lodash'
import router from '@/router'

const routesFilter = (allAsyncRoutes: RouteRecordRaw[], routesName: string[]) => {
  return allAsyncRoutes.filter((item) => {
    if (routesName.includes(item.name as string)) {
      if (item.children && item.children.length) {
        item.children = routesFilter(item.children, routesName)
      }
      return true
    }
  })
}

const resetRoutes = (allAsyncRoutes: RouteRecordRaw[]) => {
  allAsyncRoutes.forEach((item) => {
    router.removeRoute(item.name as string)
  })
}

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfoStore = defineStore('userInfo', {
  state: (): UserInfoState => ({
    token: getToken() as string,
    menuRoutes: [...staticRoutes],
    userInfo: {} as userInfo
  }),

  actions: {
    // 登录
    async login(username: string, password: string) {
      const res = await reqLogin(username, password)
      if (res.code === 20000) {
        setToken(res.data.token)
        this.token = res.data.token
      } else {
        Promise.reject(res.message)
      }
    },

    // 获取用户信息
    async getInfo() {
      const res = await reqUserInfo()
      if (res.code === 20000) {
        this.userInfo = res.data
        const cloneAllAsyncRoute = cloneDeep(allAsyncRoutes)
        const menuRoutes = routesFilter(cloneAllAsyncRoute, res.data.routes)
        menuRoutes.concat(otherRoutes).forEach((item) => {
          router.addRoute(item)
        })
        this.menuRoutes = staticRoutes.concat(menuRoutes, otherRoutes)
      } else {
        Promise.reject(res.message)
      }
    },

    // 退出功能
    async reset() {
      const res = await reqLogOut()
      if (res.code === 20000) {
        removeToken()
        resetRoutes(allAsyncRoutes)
        this.userInfo = {} as userInfo
        this.token = ''
      }
    }
  }
})
